﻿using System.Runtime.Serialization;
using Ooaavee.Data.Model;

namespace Ooaavee.Data.Queries
{
    [DataContract]
    public sealed class QueryResultRow
    {
        private readonly object _lock = new object();

        [DataMember]
        private QueryResultRowValueCollection _values;

        [DataMember]
        private DependencyCollection _dependencies;

        [DataMember]
        public QueryResult Parent { get; set; }

        public QueryResultRowValueCollection Values
        {
            get { return _values ?? (_values = new QueryResultRowValueCollection()); }
        }

        public DependencyCollection Dependencies
        {
            get
            {
                lock (_lock)
                {
                    if (_dependencies == null)
                    {
                        _dependencies = new DependencyCollection();

                        foreach (Column column in Parent.Table.Columns)
                        {
                            foreach (Column foreignKeyColumn in column.LinkedByColumns)
                            {
                                _dependencies.Add(new Dependency { Parent = this, Column = foreignKeyColumn });
                            }
                        }
                    }
                    return _dependencies;                    
                }
            }
        }

        internal bool Equals(QueryResultRow comp)
        {
            foreach (QueryResultRowValue myValue in Values)
            {
                QueryResultRowValue compValue = comp.Values[myValue.Column];
                if (myValue.Equals(compValue) == false)
                {
                    return false;
                }
            }
            return true;
        }

    }
}
